/**
 * 四海兄弟工作小组，群号:160517807
 * @author 乔继承
 * @date 2014年1月18日 下午12:55:58 
 * @version V1.0   
 */
package org.mcpro.common.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.mcpro.common.dao.IDictObjectDAO;
import org.mcpro.common.util.ObjectUtil;
import org.mcpro.core.dao.impl.BaseDAOImpl;
import org.mcpro.core.model.DictObject;
import org.mcpro.core.model.DictObject2field;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;

/**
 * 
 * @author 乔继承
 * @date 2014年1月18日 下午12:55:58
 * 
 */
public class DictObjectDAOImpl extends BaseDAOImpl implements IDictObjectDAO {
	private Logger logger = Logger.getLogger(this.getClass());

	@Override
	public int createTable(DictObject dictObject) {
		String sql = null;
		int result = -1;
		try {
			sql = dictObject.getCreateTableSql();
			JdbcTemplate jdbcTemplate = new JdbcTemplate(this.getDataSource());
			result = jdbcTemplate.update(sql);
		} catch (DataAccessException e) {
			logger.error("执行创建数据库的命令失败，sql语句为:" + sql, e);
			e.printStackTrace();
		}
		return result;
	}

	@Override
	public void saveDictObject(DictObject dictObject) {
		String insertDictObject = null;
		List<String> insertDictObject2fields = null;
		if (ObjectUtil.isNotEmpty(dictObject)) {
			insertDictObject = dictObject.getInsertDictObjectSql();
			insertDictObject2fields = dictObject
					.getInsertDictObject2FieldSqls();
		}
		int fieldLength = insertDictObject2fields.size();
		String[] sql = new String[fieldLength + 1];
		try {
			insertDictObject2fields.toArray(sql);
			sql[fieldLength] = insertDictObject;
			JdbcTemplate jdbcTemplate = new JdbcTemplate(this.getDataSource());
			jdbcTemplate.batchUpdate(sql);
		} catch (DataAccessException e) {
			logger.error("执行创建数据库的命令失败，sql语句为:" + sql, e);
			e.printStackTrace();
		}
	}

	@Override
	public List<DictObject> getDictObjectList(String... ids) {
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT dobj.id,dobj.sobjectName,dobj.suiName,dobj.stableName,dobj.snote FROM dict_object dobj");
		if (ObjectUtil.isNotEmpty(ids)) {
			sql.append(" where dobj.id in(");
			int i = 1;
			int length = ids.length;
			for (String id : ids) {
				sql.append("'").append(id).append("'");
				if (length != i++) {
					sql.append(",");
				}
			}
			sql.append(")");
		}
		JdbcTemplate jdbcTemplate = new JdbcTemplate(this.getDataSource());
		final List<DictObject> list = new ArrayList<DictObject>();
		jdbcTemplate.query(sql.toString(), new RowCallbackHandler() {
			DictObject dictObject = null;

			@Override
			public void processRow(ResultSet rs) throws SQLException {
				do {
					String id = rs.getString("id");
					String sobjectName = rs.getString("sobjectName");
					String suiName = rs.getString("suiName");
					String stableName = rs.getString("stableName");
					String snote = rs.getString("snote");
					dictObject = new DictObject(id, sobjectName, suiName,
							snote, stableName);
					list.add(dictObject);
				} while (rs.next());
			}

		});
		return list;
	}

	@Override
	public List<DictObject2field> getDictObject2FieldList(String... idObject) {

		final List<DictObject2field> list = new ArrayList<DictObject2field>();
		StringBuffer sql = new StringBuffer();
		sql.append("select dof.id,dof.idObject,dof.sfieldName,dof.sdbtype,")
				.append("dof.ifieldLength,dof.bisNull,dof.defaultValue,dof.bprimaryKey,dof.suiName,dof.snote")
				.append(" from dict_object2field dof");
		if (ObjectUtil.isNotEmpty(idObject)) {
			int length = idObject.length;
			sql.append(" where dof.idObject in(");
			for (int i = 1; i <= length; i++) {
				sql.append("?");
				if (i < length) {
					sql.append(",");
				}
			}
			sql.append(")");
		}

		JdbcTemplate jdbcTemplate = new JdbcTemplate(this.getDataSource());
		jdbcTemplate.query(sql.toString(), idObject, new RowCallbackHandler() {
			DictObject2field dof = null;

			@Override
			public void processRow(ResultSet rs) throws SQLException {
				do {
					String id = rs.getString("id");
					String idObject = rs.getString("idObject");
					String sfieldName = rs.getString("sfieldName");
					String sdbtype = rs.getString("sdbtype");
					int ifieldLength = rs.getInt("ifieldLength");
					boolean bisNull = rs.getBoolean("bisNull");
					String defaultValue = rs.getString("defaultValue");
					boolean bprimaryKey = rs.getBoolean("bprimaryKey");
					String suiName = rs.getString("suiName");
					String snote = rs.getString("snote");
					dof = new DictObject2field(id, idObject, sfieldName,
							sdbtype, ifieldLength, bisNull, defaultValue,
							bprimaryKey, suiName, snote);
					list.add(dof);
				} while (rs.next());
			}

		});
		return list;
	}

	@Override
	public DictObject2field getDictObject2FieldById(String id) {
		if (ObjectUtil.isEmpty(id)) {
			return null;
		}
		final List<DictObject2field> list = new ArrayList<DictObject2field>();
		String sql = "SELECT dof.id,dof.idObject,dof.sfieldName,dof.sdbtype,"
				+ "dof.ifieldLength,dof.bisNull,dof.defaultValue,dof.bprimaryKey,dof.suiName,dof.snote "
				+ "FROM dict_object2field dof WHERE dof.id=?";
		JdbcTemplate jdbcTemplate = new JdbcTemplate(this.getDataSource());
		jdbcTemplate.query(sql, new String[] { id }, new RowCallbackHandler() {
			DictObject2field dof = null;

			@Override
			public void processRow(ResultSet rs) throws SQLException {
				String id = rs.getString("id");
				String idObject = rs.getString("idObject");
				String sfieldName = rs.getString("sfieldName");
				String sdbtype = rs.getString("sdbtype");
				int ifieldLength = rs.getInt("ifieldLength");
				boolean bisNull = rs.getBoolean("bisNull");
				String defaultValue = rs.getString("defaultValue");
				boolean bprimaryKey = rs.getBoolean("bprimaryKey");
				String suiName = rs.getString("suiName");
				String snote = rs.getString("snote");
				dof = new DictObject2field(id, idObject, sfieldName, sdbtype,
						ifieldLength, bisNull, defaultValue, bprimaryKey,
						suiName, snote);
				list.add(dof);
			}

		});
		if(ObjectUtil.isNotEmpty(list)){
			return list.get(0);
		}
		return null;
	}

	@Override
	public List<DictObject2field> saveOrupdateObjectField(
			DictObject2field dictObject2field) {
		String id=dictObject2field.getId();
		if(ObjectUtil.isEmpty(id)){
			saveObjectField(dictObject2field);
		}else{
			DictObject2field field=this.getDictObject2FieldById(id);
			if(ObjectUtil.isEmpty(field)){
				saveObjectField(dictObject2field);
			}else{
				updateObjectField(dictObject2field);
			}
		}
		return this.getDictObject2FieldList(dictObject2field.getIdObject());
	}

	/**
	 * 
	 * @param dictObject2field
	 * @param tableName
	 * @return
	 * @author 乔继承
	 * @date 2014年3月16日 上午10:56:47
	 */
	private int updateObjectField(DictObject2field dictObject2field) {
		String sql=dictObject2field.getUpdateDictObject2FieldSql();
		JdbcTemplate jdbcTemplate=new JdbcTemplate(this.getDataSource());
		int result=-1;
		result=jdbcTemplate.update(sql);
		return result;
	}

	/** 
	 * @param dictObject2field
	 * @author 乔继承
	 * @return 
	 * @date 2014年3月16日 上午10:27:51
	*/ 
	private int saveObjectField(DictObject2field dictObject2field) {
		String sql=dictObject2field.getInsertDictObject2FieldSql();
		JdbcTemplate jdbcTemplate=new JdbcTemplate(this.getDataSource());
		int result=-1;
		result=jdbcTemplate.update(sql);
		return result;
	}

	@Override
	public int addColumnByField(String tableName,
			DictObject2field dictObject2field) {
		String sql=dictObject2field.getAddColumnSql(tableName);
		JdbcTemplate jdbcTemplate=new JdbcTemplate(this.getDataSource());
		int result=-1;
		result=jdbcTemplate.update(sql);
		return result;
	}

	@Override
	public int alterColumnByField(String tableName,
			DictObject2field dictObject2field) {
		DictObject2field dof=this.getDictObject2FieldById(dictObject2field.getId());
		String sql=dictObject2field.getAlterColumnSql(tableName,dof.getSfieldName());
		JdbcTemplate jdbcTemplate=new JdbcTemplate(this.getDataSource());
		int result=-1;
		result=jdbcTemplate.update(sql);
		return result;
	}

	@Override
	public List<DictObject> getObjectByProperty(String[] propertyName, Object[] value) {
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT dobj.id,dobj.sobjectName,dobj.suiName,dobj.stableName,dobj.snote FROM dict_object dobj");
		if (ObjectUtil.isNotEmpty(propertyName) && ObjectUtil.isNotEmpty(value)
				&& propertyName.length == value.length) {
			sql.append(" where");
			for(int i=1;i<=propertyName.length;i++){
				sql.append(" dobj.").append(propertyName[i-1]).append("=?");
				if(i!=propertyName.length){
					sql.append(",");
				}
			}
		}
		final List<DictObject> list=new ArrayList<DictObject>();
		JdbcTemplate jdbcTemplate = new JdbcTemplate(this.getDataSource());
		jdbcTemplate.query(sql.toString(), value, new RowCallbackHandler() {
			DictObject dictObject = null;

			@Override
			public void processRow(ResultSet rs) throws SQLException {
				do {
					String id = rs.getString("id");
					String sobjectName = rs.getString("sobjectName");
					String suiName = rs.getString("suiName");
					String stableName = rs.getString("stableName");
					String snote = rs.getString("snote");
					dictObject = new DictObject(id, sobjectName, suiName,
							snote, stableName);
					list.add(dictObject);
				} while (rs.next());
			}

		});
		return list;
	}

}
